package com.ht.medicaltreatment.activity

import android.content.Intent
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.githang.statusbar.StatusBarCompat
import com.gym.baselib.base.BaseActivity
import com.ht.medicaltreatment.R
import com.ht.medicaltreatment.adapter.NinetySixeAdapter
import com.ht.medicaltreatment.bean.CheckSampleVO
import com.ht.medicaltreatment.utils.NFCUtils
import com.ht.medicaltreatment.utils.ScanUtils
import com.ht.medicaltreatment.utils.SoundUtils
import com.ht.medicaltreatment.utils.UIDUitls
import com.ht.medicaltreatment.view.NinetySixDialog
import com.ht.medicaltreatment.viewmodel.NinetySixViewModel
import com.xgst.lib.utils.TimeUtils
import com.xgst.lib.utils.showToast
import kotlinx.android.synthetic.main.activity_ninety_six_layout.btn
import kotlinx.android.synthetic.main.activity_ninety_six_layout.recyclerView
import kotlinx.android.synthetic.main.activity_ninety_six_layout.tvCode
import kotlinx.android.synthetic.main.activity_ninety_six_layout.tvName
import kotlinx.android.synthetic.main.activity_ninety_six_layout.tvName2
import kotlinx.android.synthetic.main.activity_ninety_six_layout.tvProjectName
import kotlinx.android.synthetic.main.activity_ninety_six_layout.tvStatus
import kotlinx.android.synthetic.main.activity_ninety_six_layout.tvTime
import kotlinx.android.synthetic.main.activity_ninety_six_layout.tvUserName
import kotlinx.android.synthetic.main.include_title_layout.imgBack
import kotlinx.android.synthetic.main.view_stub_layout.imgViewStubProgress
import kotlinx.android.synthetic.main.view_stub_layout.tvViewStubProgress
import kotlinx.android.synthetic.main.view_stub_layout.viewStub

/**
 * 96孔核验
 */
class NinetySixDetailActivity : BaseActivity() {
    private val model by viewModels<NinetySixViewModel>()
    private var isStart = false
    private var checekSampleId = ""
    private var currentPositon = 0
    private lateinit var adapter:NinetySixeAdapter
    private val scanList = mutableListOf<String>()
    private val list = mutableListOf<CheckSampleVO>()
    private lateinit var dialog:NinetySixDialog
    private var isChecked = true

    private val v9100 by lazy {
        intent.getBooleanExtra("version",false)
    }

    override fun getLayoutId() = R.layout.view_stub_layout

    override fun init() {

        StatusBarCompat.setStatusBarColor(this,getColor(R.color.white))

        viewStub.setOnInflateListener { viewStub, view ->
            tvViewStubProgress.visibility = View.GONE
            imgViewStubProgress.visibility = View.GONE
            initView()
        }
        viewStub.postDelayed({
            viewStub.layoutResource = R.layout.activity_ninety_six_layout
            viewStub.inflate()
        },300)

        if(v9100){
            ScanUtils.init(false)
            LogUtils.i("初始化了")
        }else{
            NFCUtils(this)
        }
    }

    private fun initView() {
        val id = intent.getIntExtra("id",0)
        setTitle("96孔核验订单详情")
        adapter = NinetySixeAdapter()
        recyclerView.adapter = adapter

        dialog = NinetySixDialog(this)

        //开始核验
        btn.setOnClickListener{
            if(isStart){
                btn.text = "开始核验"
                btn.setBackgroundColor(getColor(R.color.blue))
                if(v9100){
                    ScanUtils.close()
                }
            }else{
                btn.text = "停止核验"
                btn.setBackgroundColor(getColor(R.color.yellow))
                startScan()
            }
            isStart = !isStart
        }

        showProgress()
        model.order96Detail("$id",{
            TimeUtils.countDownOneTime(2,{
                dismissProgress()
            })
            it?.let { bean ->
                list.clear()
                recyclerView.layoutManager = GridLayoutManager(this,bean.col)
                adapter.setNewInstance(bean.checkSampleVOList)
                //保存已存在的试管位置信息
                bean.checkSampleVOList.forEachIndexed {index,it ->
                    it.position = index+1
                    if(it.locationStatus == 1){
                        list.add(it)
                        //LogUtils.i("存在的试管 ${it.position},${it.location},${it.locationStatus}")
                    }
                }
                if(list.size > 0){
                    val item = list.firstOrNull { it.checkStatus == 0 }
                    if(item != null){
                        //最初的位置角标
                        currentPositon = item.position-1
                        checekSampleId = list[currentPositon].checkSampleId
                    }
                }
                tvName.text = "分析批名称: ${bean.name}"
                tvName2.text = bean.name
                tvTime.text = bean.createTime
                tvCode.text = bean.serialNumber
                tvProjectName.text = bean.project.name
                tvUserName.text = bean.user.name
                if(bean.status == 0){
                    tvStatus.text = "未核验"
                    isChecked = false
                    tvStatus.setTextColor(getColor(R.color.red))
                }else if(bean.status == 1){
                    tvStatus.text = "已核验"
                    isChecked = true
                    btn.isEnabled = false
                    btn.setBackgroundColor(getColor(R.color.color97))
                    btn.text = "已核验"
                    btn.setTextColor(getColor(R.color.white))
                }else if(bean.status == 3){
                    tvStatus.text = "核验中"
                    isChecked = false
                    tvStatus.setTextColor(getColor(R.color.yellow))
                }else{
                    tvStatus.text = "${bean.status}"
                }
            }
        },{
            dismissProgress()
            showToast(it)
        })

        imgBack.setOnClickListener {
            finish()
        }
    }

    private fun startScan() {
        if(!v9100)return
        LogUtils.i("开始核验")
        ScanUtils.open {
            LogUtils.i(it)
            if(!dialog.isShowing){
                if(scanList.contains(it)){
                    //showToast("已扫描过")
                }else{
                    scanList += it
                    submitChecked(it)
                }
            }
        }
    }

    //上传后台
    private fun submitChecked(it: String) {
        showProgress()
        model.submitCheck(checekSampleId,it,{
            dismissProgress()
            if(it == "200"){
                SoundUtils.playSound(SoundUtils.CHECK_SUCCESS)
                //核验成功
                val bean = list[currentPositon]
                bean.checkStatus = 1
                adapter.setData(bean.position-1,bean)
                if (currentPositon >= list.size - 1){
                    isStart = false
                    showToast("核验完成")
                    setCheckOver()
                    if(v9100){
                        ScanUtils.close()
                    }
                }else{
                    currentPositon++
                    checekSampleId = list[currentPositon].checkSampleId
                }
            }else{
                SoundUtils.playSound(SoundUtils.CHECK_ERROR)
                dialog.showDialog(it?:"",{
                    //跳过
                    jump()
                },{
                    //从新核验
                    scanList.removeLastOrNull()
                })
            }
        },{
            dismissProgress()
            showToast(it)
        })
    }

    private fun jump() {
        showProgress()
        model.jump(checekSampleId,{
            dismissProgress()

            val bean = list[currentPositon]
            bean.checkStatus = 2
            adapter.setData(bean.position-1,bean)
            if(currentPositon == list.size - 1){
                isStart = false
                setCheckOver()
                if(v9100){
                    ScanUtils.close()
                }
            }else{
                currentPositon++
                checekSampleId = list[currentPositon].checkSampleId
            }
        },{
            dismissProgress()
            showToast(it)
        })
    }

    //状态变成已核验
    private fun setCheckOver() {
        isChecked = true
        btn.isEnabled = false
        btn.setBackgroundColor(getColor(R.color.color97))
        btn.text = "已核验"
        btn.setTextColor(getColor(R.color.white))
        tvStatus.text = "已核验"
        tvStatus.setTextColor(getColor(R.color.black))
    }

    override fun onResume() {
        super.onResume()
        if(v9100)return
        //开启前台调度系统
        NFCUtils.mNfcAdapter.enableForegroundDispatch(this,NFCUtils.mPendingIntent,NFCUtils.mIntentFilter, NFCUtils.mTechList)
    }

    override fun onPause() {
        super.onPause()
        if(v9100)return
        //关闭前台调度系统
        NFCUtils.mNfcAdapter.disableForegroundDispatch(this)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if(v9100 || isChecked)return
        var uid: String = NFCUtils.readNFCId(intent)
        uid = UIDUitls.sort(uid)
        submitChecked(uid)
    }

    override fun onDestroy() {
        super.onDestroy()
        if(!v9100)return
        ScanUtils.onDestroy()
    }
}
